const {
  queryAllAssetsType
} = require('../../api/assetsType')
const {
  queryCompanyOptions
} = require('../../api/company')
const {
  quaryAssetsList,
  delMultipleAssets,
  doAssetsBindingQRCode
} = require('../../api/assets')
const {
  clearEmptyKey
} = require('../../utils/clearEmptyKey')
const {
  to,
  openLoading,
  closeLoading,
  showToast,
  routeWithToken
} = getApp()
Page({
  data: {
    value: '',
    loadingType: '',
    dataList: [],
    pagination: {
      page: 1,
      limit: 10
    },
    searchAreaOptions: [],
    searchValue: {},
    total: 0
  },

  onLoad() {
    this.resetData()
    this.getAllPickerOptions()
    this.getQuaryAsserts()
  },

  async getAllPickerOptions() {
    const [err, [company, assetsType]] = await to(Promise.all([this.getCompanyList(), this.getQueryAllAssetsType()]))

    if (!err) {
      const options = [{
          title: '资源类型',
          valueKey: 'assetsTypeName',
          nodeKey: 'assetsTypeId',
          options: [{
              assetsTypeId: '',
              assetsTypeName: '全部'
            },
            ...assetsType
          ]
        },
        {
          title: '单位',
          valueKey: 'companyName',
          nodeKey: 'companyId',
          options: [{
              companyId: '',
              companyName: '全部'
            },
            ...company
          ]
        }
      ]
      this.setData({
        searchAreaOptions: options
      })
    }
  },

  async getCompanyList() {
    const [err, data] = await to(queryCompanyOptions({}));
    if (!err) {
      return Promise.resolve(data)
    }
    return Promise.reject(err)
  },
  async getQueryAllAssetsType() {
    const [err, data] = await to(queryAllAssetsType({}))
    if (!err) {
      return Promise.resolve(data)
    }
    return Promise.reject(err)
  },

  handleSearchChange(event) {
    this.setData({
      searchValue: event.detail
    })
    this.resetData()
    this.getQuaryAsserts()
  },

  async getQuaryAsserts(openL = true) {
    const params = {
      assetsUserName: this.data.searchValue.inputVal || '',
      assetsTypeId: this.data.searchValue.assetsTypeId,
      ...this.data.pagination
    }

    if (this.data.searchValue.companyId || this.data.searchValue.companyId === 0) {
      params.companyIds = [this.data.searchValue.companyId];
    }

    clearEmptyKey(params)
    openL && openLoading()
    const [err, data] = await to(quaryAssetsList(params))
    closeLoading()
    if (!err) {
      const {
        dataList
      } = this.data
      this.setData({
        dataList: dataList.concat(data.dataList),
        total: data.total
      })

      if (data.total === 0) {
        this.setData({
          loadingType: 'empty'
        })
        return
      }

      if (this.data.dataList.length >= data.total) {
        this.setData({
          loadingType: 'end'
        })
      }
    }
  },

  handleToAddDevice() {
    wx.setStorageSync('device-manager', null)
    routeWithToken('./device-form/index?type=add')
  },

  handleScrolltolower() {
    const {
      total,
      pagination,
      dataList
    } = this.data

    if (dataList.length < total) {
      let page = pagination.page;
      page++
      this.setData({
        loadingType: 'loading',
        ['pagination.page']: page
      })
      this.getQuaryAsserts(false)
    }
  },

  handleToRoute(event) {
    const item = JSON.stringify(event.detail)

    wx.setStorageSync('device-manager', item)
    routeWithToken('./device-form/index?type=review')
  },
  handleEdit(event) {
    const item = JSON.stringify(event.detail)
    wx.setStorageSync('device-manager', item)
    routeWithToken('./device-form/index?type=edit')
  },
  handleDelete(event) {
    wx.showModal({
      content: '是否删除?',
      title: '提示',
      success: (res) => {
        if (res.confirm) {
          this.deleteData(event.detail)
        }
      }
    })
  },

  async deleteData(param) {
    const AssetsDeleteParam = {
      'assetsIds[0]': [param.assetsId] // TODO
    }
    openLoading()
    const [err] = await to(delMultipleAssets(AssetsDeleteParam))
    closeLoading()
    if (!err) {
      this.resetData()
      this.getQuaryAsserts()
    }
  },

  resetData() {
    this.setData({
      ['pagination.page']: 1,
      dataList: [],
      loadingType: '',
      total: 0
    })
  },

  checkIsBinding(item) {
    return new Promise((resolve) => {
      if (item.qrCodeId) {
        wx.showModal({
          title: '提示',
          content: '该设备已绑定二维码，是否重新绑定?',
          success(res) {
            if (res.confirm) {
              resolve()
            }
          }
        })
      } else {
        resolve()
      }
    })
  },

  handleBinding(event) {
    const self = this;
    this.checkIsBinding(event.detail).then(() => {
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          const qrCodeId = self.getQrCode(res.result)
          const params = {
            assetsId: event.detail.assetsId,
            qrCodeId
          }
          self.onBinding(params)
        }
      });
    })
  },

  getQrCode(data) {
    const list = data.split('/')
    return list[list.length - 1]
  },

  async onBinding(params) {
    openLoading()
    const [err] = await to(doAssetsBindingQRCode(params))
    closeLoading()
    if (!err) {
      showToast({
        message: '绑定成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            this.resetData()
            this.getQuaryAsserts()
          }, 1000)
        }
      })
    }
  }
})